<template>
  <!-- fqc及oqc, ipqc检验报表界面 -->
  <div>
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :search.sync="query"
        :data="data"
        :page.sync="page"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        :key="timer"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true" v-if="isHasExportPermission">导出</el-button>
        </template>
        <template slot="menuRight">
          <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
        </template>
        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" @click="viewReport(row.documentType, row)" icon="el-icon-view" size="small" v-if="isHasPermission">查看检验报告</el-button>
        </template>
      </avue-crud>
      <export-comp ref="exportComp" page-api-url="mes-product/inspection-document/documentPage" :option="option" :page="page" :query="query" :file-name="excelName">
      </export-comp>
    </basic-container>
  </div>
</template>

<script>
import { getPage, getDetail } from '@/api/quality/checkLists.js';

import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
export default {
  components: {
    exportComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'CHECKREPORTS',
      form: {
        deptId: '',
        lineId: ''
      },
      search: {},
      query: {},
      isLock: true,
      loading: true,
      timer: null,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 510px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        // searchMenuSpan: 120,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        dialogClickModal: false,
        // labelWidth: 120,
        searchLabelWidth: 120,
        // searchSpan: 6,
        addBtn: false,
        // 操作栏不展示
        menu: true,
        editBtn: false,
        delBtn: false,
        // 查看
        viewBtn: false,
        columnBtn: false,
        column: [
          {
            label: '类型',
            prop: 'documentType',
            type: 'select',
            search: true,
            hide: true,
            searchOrder: 1,
            dicData: [
              {
                label: '巡检',
                value: 'IPQC'
              },
              {
                label: '首检',
                value: 'FAI'
              },
              {
                label: '末检',
                value: 'LAI'
              }
            ],
            change: (value) => {
              this.selectRouteObj.documentType = value.value;
            }
          },
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true,
            minWidth: 150,
            searchOrder: 1
          },
          {
            label: '工单号',
            minWidth: 150,
            search: true,
            searchOrder: 2,
            prop: 'sourceNo'
          },
          {
            label: '销售订单号',
            minWidth: 150,
            search: true,
            searchOrder: 8,
            prop: 'salesOrderNo'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            minWidth: 100,
            search: true,
            searchOrder: 3
          },
          {
            label: '产品名称',
            minWidth: 100,
            prop: 'partName'
          },
          {
            label: '产品规格',
            minWidth: 100,
            prop: 'partModel'
          },
          {
            label: '客户名称',
            minWidth: 100,
            hide: true,
            prop: 'partnerName'
          },
          {
            label: '报检数量',
            prop: 'sendExamineQuantity'
          },
          {
            label: '检验数量',
            prop: 'examineQuantity'
          },
          {
            label: '合格数量',
            prop: 'okQuantity'
          },
          {
            label: '不合格数量',
            prop: 'ngQuantity'
          },
          {
            label: '检验结果',
            prop: 'examineResult',
            type: 'select',
            search: true,
            searchOrder: 6,
            // dicFlag: false,
            dicUrl: '/api/blade-system/dict/dictionary?code=examineResult',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '检验日期',
            minWidth: 150,
            prop: 'examineDate',
            type: 'datetime',
            search: true,
            searchOrder: 7,
            searchType: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '检验人员',
            prop: 'examineByName'
          },
          {
            label: '抽检sn',
            prop: 'objectSns'
          }
        ]
      },
      data: [],
      dialogVisible: false,
      dialogForm: {
        isQualified: null
      },
      // 车间列表
      workshopList: [],
      repairSuccessVisible: false,
      repairSuccessForm: {
        scrapReason: ''
      },
      rulesSuccessForm: {
        scrapReason: [{ required: true, message: '请输入报废原因', trigger: 'blur' }]
      },
      // 判断是在那个routeName下的
      selectRouteObj: {
        documentType: 'FQC'
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    excelName() {
      const routerMap = {
        1: 'FQC检验报表',
        2: 'OQC检验报表',
        3: 'IPQC检验报表'
      };
      const path = this.$route.path.split('/')[3];
      console.log(this.$route.path.split('/'));
      return routerMap[path];
    },
    isHasPermission() {
      // 1: FQC | 2: OQC | 3: IPQC
      if (this.$route.path === '/quality/checkReports/1') {
        return this.permission.checkReports_view_report;
      } else if (this.$route.path === '/quality/checkReports/2') {
        return this.permission.oqcReports_view_report;
      } else {
        return this.permission.ipqReport_view_report;
      }
    },
    isHasExportPermission() {
      // 1: FQC | 2: OQC | 3: IPQC
      if (this.$route.path === '/quality/checkReports/1') {
        return this.permission.checkReports_export_report;
      } else if (this.$route.path === '/quality/checkReports/2') {
        return this.permission.oqcReports_export_report;
      } else {
        return this.permission.ipqReport_export_report;
      }
    }
  },
  mounted() {
    if (this.isLock) {
      this.onLoad(this.page);
      this.$nextTick(() => {
        this.$structuralSplit();
      });
    }
  },
  methods: {
    viewReport(documentType, row) {
      let reportTemplateName = this._get(row, 'inspectionTemplate.reportTemplateName', '');
      switch (documentType) {
        case 'IPQC':
          window.open(`${this.website.reportUrl}/preview?_u=blade-${reportTemplateName}&qcId=${row.id}`);
          break;
        case 'FQC':
          window.open(`${this.website.reportUrl}/preview?_u=blade-${reportTemplateName}&qcId=${row.id}`);
          break;
        case 'OQC':
          window.open(`${this.website.reportUrl}/preview?_u=blade-${reportTemplateName}&qcId=${row.id}`);
          break;
        case 'FAI':
          window.open(`${this.website.reportUrl}/preview?_u=blade-${reportTemplateName}&qcId=${row.id}`);
          break;
        case 'LAI':
          window.open(`${this.website.reportUrl}/preview?_u=blade-${reportTemplateName}&qcId=${row.id}`);
          break;
      }
      // this.$route.path === '/quality/checkReports/1'
      // this.selectRouteObj.documentType === 'IPQC'
      //   if (this.$route.path === '/quality/checkReports/3') {
      //     window.open(`${this.website.reportUrl}/preview?_u=blade-IPQC巡检记录表.ureport.xml&qcId=${id}`);
      //   } else {
      //     window.open(`${this.website.reportUrl}/preview?_u=blade-FQC检验报告表.ureport.xml&qcId=${id}`);
      //   }
      // this.$router.push({ path: `/myiframe/urlPath?name=preview-11&src=http://192.168.1.199:8108/ureport/preview?_u=blade-11.ureport.xml&ipqcId=${id}` });
    },
    init() {
      const columnItem = this.findObject(this.option.column, 'partnerName');
      const sendExamineQuantity = this.findObject(this.option.column, 'sendExamineQuantity');
      const typeObj = this.findObject(this.option.column, 'documentType');
      const salesOrderNo = this.findObject(this.option.column, 'salesOrderNo');
      switch (this.$route.path) {
        case '/quality/checkReports/1':
          this.option.column[2].label = '工单号';
          this.selectRouteObj.documentType = 'FQC';
          columnItem.hide = true;
          typeObj.hide = true;
          typeObj.search = false;
          sendExamineQuantity.hide = false;
          salesOrderNo.hide = false;
          salesOrderNo.search = true;
          // this.option.searchMenuSpan = 18;
          break;
        case '/quality/checkReports/2':
          this.option.column[2].label = '发货单号';
          this.selectRouteObj.documentType = 'OQC';
          columnItem.hide = false;
          typeObj.hide = true;
          typeObj.search = false;
          sendExamineQuantity.hide = false;
          salesOrderNo.hide = true;
          salesOrderNo.search = false;
          // this.option.searchMenuSpan = 18;
          break;
        case '/quality/checkReports/3':
          this.option.column[2].label = '工单号';
          this.query.docType = 'IPQC,FAI,LAI';
          columnItem.hide = true;
          typeObj.hide = false;
          typeObj.search = true;
          sendExamineQuantity.hide = true;
          salesOrderNo.hide = false;
          salesOrderNo.search = true;
          // this.option.searchMenuSpan = 12;
          break;
      }
      // this.refreshChange()
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.examineDate && params.examineDate.length > 0) {
        params.startExamineDate = params.examineDate[0];
        params.endExamineDate = params.examineDate[1];
        delete params.examineDate;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.init();
      this.loading = true;
      if (this.$route.path !== '/quality/checkReports/3') {
        this.query.documentType = this.selectRouteObj.documentType;
      } else {
        this.query.docType = !params.documentType ? 'IPQC,FAI,LAI' : params.documentType;
      }
      this.query.status = 2;
      this.query.descs = 'send_examine_date';
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        if (this.$route.path !== '/quality/checkReports/3') {
          this._forEach(this.data, (item) => {
            if (!item.sendExamineQuantity) {
              item.okQuantity = item.examineQuantity;
            }
          });
        }
        this.loading = false;
        this.selectionClear();
      });
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  },
  watch: {
    async $route() {
      let whiteList = ['/quality/checkReports/1', '/quality/checkReports/2', '/quality/checkReports/3'];
      if (whiteList.includes(this.$route.path)) {
        this.isLock = false;
        this.newKey();
        this.init();
        this.page = {
          pageSize: 20,
          currentPage: 1,
          total: 0
        };
        this.query = {};
        await this.onLoad(this.page);
        this.$nextTick(() => {
          this.$structuralSplit();
        });
      }
    }
  }
};
</script>

<style></style>
